//
//  HMComposeViewController.swift
//  CZBKWB31
//
//  Created by Linkon Y on 16/8/17.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
class HMComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    // MARK: - 监听方法
    @objc private func cancelAction(){
        //取消键盘第一个响应
    composeTextView.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendAction(){
        printLog("发布成功")
        //判断发布类型
        
        /**
         *  遍历富文本
         
         - 遍历到的结果
         - 遍历到的范围
         - 指针是否停止
         
         */
        //定义一个字符串  保存内容
        var alltext: String = ""
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options:
        []) { (result, range, _) in
            //代表文字附件（自定义的）
            if let attachment = result["NSAttachment"] as? HMTextAttachment{
                
                alltext += attachment.emoticonModel?.chs ?? ""
            }else{
                //普通字符串(截取对应的字符串)
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                alltext += str
            }
        }
        //发布微博
        print(alltext)
        composePicView.imageList.count == 0 ? updata(alltext) : upload(alltext)
    }
    
    // MARK: - 设置UI
    @objc private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setNav()
        // MARK: - 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePicView)
        
        // MARK: - 添加约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeBottomView.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        composePicView.snp_makeConstraints { (make) in
            let wh = SCREENW - 20
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
            make.size.equalTo(CGSize(width:wh, height: wh))
        }
        
        
        //  监听底部view 中按钮点击回调 02
        composeBottomView.closure = {[weak self] (type: HMComposeBottomViewType) -> () in
            switch type {
            case .Picture:
                print("图片")
                //注意强引用问题
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .Add:
                print("+")
          
            }
  
        }
        //配图闭包回调 02
        composePicView.closure = { [weak self] in
            // 04
            self?.selectImage()
        }
        //注册通知，监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //注册通知 监听自定义键盘删除按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteBtnNofi", name: WBEMOTICONDELETEBTNNOTIFICATION, object: nil)
        //监听自定义表情键盘按钮点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonBtnNoti:", name: WBEMOTICONEBTNNOTIFICATION, object: nil)
     
    }
    
    //删除按钮事件
    func emoticonDeleteBtnNofi(){
        //回车 每次删除一个
       composeTextView.deleteBackward()
    }
    //表情键盘按钮点击事件
    func emoticonBtnNoti(noti: NSNotification){
        //判断是否为NIL  而且转成HMEmoticonModel
        guard let emoticonModel = noti.object as? HMEmoticonModel else{
        return
        }
      //判断是emoji 还是图片表情
        if emoticonModel.isEmoji{
            //十六进制转字符串
            let str = (emoticonModel.code ?? "" as NSString).emoji()
            //
            composeTextView.insertText(str)
        }else{
            //获取当前composeTextView 已有的副文本
        let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
        //图片表情
        //创建一个文字附件
          let att = HMTextAttachment()
        //赋值
            att.emoticonModel = emoticonModel
        //设置image
            let image = UIImage.emoticonImage(emoticonModel)
            att.image = image
        //切记设置bouns
            //计算行高
            let lineHeight = UIFont.systemFontOfSize(16).lineHeight
            //-4 微调值
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        //创建一个不可变的副文本
            let attr = NSAttributedString(attachment: att)
            //获取光标的指定范围
            let selectRange = composeTextView.selectedRange
            //替换方式
            allAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            //统一字体
            allAttr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16) ], range: NSRange(location: 0, length: allAttr.length))
//            //插入方式(也不对)
//            allAttr.insertAttributedString(attr, atIndex: selectRange.location)
            //拼接副文本
//            allAttr.appendAttributedString(attr)//有BUG
            //添加副文本
            composeTextView.attributedText = allAttr
            //更改光标
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            //发送一个系统通知  隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            //使用代理 实现发布
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
    
    //监听键盘改变
    func keyboardWillChangeFrame(noti:NSNotification){
//     print(noti.userInfo)
        //动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
        return
        }
        //判断是是否为NIL 而且可否转成NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        //获取CGRect
        let newRect = rect.CGRectValue()
        //更新约束
        composeBottomView.snp_updateConstraints{ (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
            
        }
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
        
    }
    
     // MARK: - 设置导航
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
        
    }
    
     // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        //用户昵称
        let name = HMUserAccountViewModel.sharedTools.userAccount!.screen_name!
        //显示内容
        let str = "发微博\n\(name)"
        //获取范围
        let range = (str as NSString).rangeOfString(name)
        //初始化一个副文本  可变副文本
        let attr = NSMutableAttributedString(string: str)
        //设置副文本
        attr.addAttributes([NSForegroundColorAttributeName : AppThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(12)],range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.attributedText = attr
        lab.sizeToFit()
        return lab
    }()
    //自定义textView
    private lazy var composeTextView: HMComposeTextView = {
        let view = HMComposeTextView()
        view.delegate = self
        view.font = UIFont.systemFontOfSize(16)
        view.placeholder = "哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
        view.textColor = UIColor.grayColor()
        //可以上下移动
        view.alwaysBounceVertical = true
        return view
    }()
    //自定义底部视图
    private lazy var composeBottomView: HMComposeBottomView = HMComposeBottomView()
    //配图
    private lazy var composePicView: HMComposePicView = HMComposePicView()
    //自定义表情键盘
    private lazy var emoticonKeyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
    
    
    //析构函数 移除通知
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension HMComposeViewController{
    //发布文字文本刷新
    func updata(status: String){
        HMNetworkTool.sharedTools.composeUpdata(status, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功！")
        }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败！")
        }
    }
    //发布文字图片微博
    func upload(status: String){
        HMNetworkTool.sharedTools.composeUpload(status, images: composePicView.imageList, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功！")
        }) { (error) in
            SVProgressHUD.showErrorWithStatus("发布失败！")
        }
    }
}

 // MARK: - 处理composebotton图片按钮的点击事件
extension HMComposeViewController{
    //选择图片
    func selectImage(){
    let pickVc = UIImagePickerController()
        //设置代理
        pickVc.delegate = self
    self.presentViewController(pickVc, animated: true, completion: nil)
    }
    //切换键盘
    func switchKeyboard(){
        //系统键盘
        if composeTextView.inputView == nil {
            composeTextView.inputView = emoticonKeyboardView  //自定义键盘
            composeBottomView.isEnoticon = true
        }else{
        //显示自定义键盘
          composeTextView.inputView = nil //编程系统键盘
            composeBottomView.isEnoticon = false
        }
        //刷新
        composeTextView.reloadInputViews()
        //成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}

extension HMComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //老方法
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        composeTextView.backgroundColor = UIColor(patternImage:image)
//         picker.dismissViewControllerAnimated(true, completion: nil)
//    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//        print(info)
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
//        let image1 = UIImage.dealImageScale(image, width: 600)
//        let data = UIImagePNGRepresentation(image1)
//        data?.writeToFile("/Users/Linkon/Desktop/哈哈.png", atomically: false)
//        print(image)
//        composeTextView.backgroundColor = UIColor(patternImage:image)
        //关闭控制器
        //添加图片
        composePicView.addImage(UIImage.dealImageScale(image, width: 600))
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

 // MARK: - UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //取消键盘第一响应
        self.composeTextView.resignFirstResponder()
    }

}



